import 'leaflet/dist/leaflet.css'
import L from 'leaflet'
import 'leaflet-draw'
import 'leaflet-draw/dist/leaflet.draw.css'
import icon from 'leaflet/dist/images/marker-icon.png'

const createMap = (divId, options) => {
  return L.map(divId, options)
}
const TIANDITUKEY = '4bc899bbc69627f359a7ec2b3dfd8cc6'
const TIANDITU = {
  wmts: 'http://{s}.tianditu.gov.cn/vec_c/wmts?tk=' + TIANDITUKEY,
  wmts_bz: 'http://{s}.tianditu.gov.cn/cva_c/wmts?tk=' + TIANDITUKEY
}

//添加创建地图的函数
const createTileLayer = (map, url, options) => {
  let tileLayer = L.tileLayer(url, options)
  tileLayer.addTo(map)
  return tileLayer
}

const createDrawControl = (map, drawCreatedBack, options) => {
  let drawControl = new L.Control.Draw(options)
  map.on(L.Draw.Event.CREATED, drawCreatedBack)
  return drawControl
}

const createFeatureGroup = (map) => {
  let featureGroup = new L.FeatureGroup()
  map.addLayer(featureGroup)
  return featureGroup
}

const createTDTWMTSLayer = (map, options) => {
  let tileLayer = L.tileLayer('http://{s}.tianditu.gov.cn/vec_c/wmts?layer=vec&style=default&tilematrixset=c&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}&tk=4bc899bbc69627f359a7ec2b3dfd8cc6', {
      maxZoom: options.maxZoom || 17,
      minZoom: 2,
      tileSize: 256,
      zoomOffset: 1,
      subdomains: ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7']
    }
  )
  let tileLayer_bz = L.tileLayer('http://{s}.tianditu.gov.cn/cva_c/wmts?layer=cva&style=default&tilematrixset=c&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}&tk=4bc899bbc69627f359a7ec2b3dfd8cc6', {
      maxZoom: options.maxZoom || 17,
      minZoom: 2,
      tileSize: 256,
      zoomOffset: 1,
      subdomains: ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7']
    }
  )
  tileLayer.addTo(map)
  tileLayer_bz.addTo(map)
  return tileLayer
}

const createMapArea = (map, drawGroup) => {
  map.on(L.Draw.Event.CREATED, event => {
    const { layer, layerType } = event
    if (layerType === 'polygon' || layerType === 'rectangle') {
      //layer.getLatLngs()得到的多边形的经纬度集合，多边形得到的是一个二维数组，这里要取里面的数组，一定要注意
      let latlng = layer.getLatLngs()[0]
      //一个自定义的计算面积的函数
      let area = formatArea(latlng)
      addMeasureMarker(area, [latlng[0].lat, latlng[0].lng], drawGroup)//把画图之后计算的结果添加到地图上
    } else if (layerType === 'polyline') {
      //polyline得到的是一个一维数组，直接使用
      let latlng = layer.getLatLngs()
      //一个自定义的计算长度的函数
      let distance = formatLength(latlng)
      addMeasureMarker(distance, [latlng[0].lat, latlng[0].lng], drawGroup)
    } else if (layerType === 'circle') {
      //polyline得到的是一个一维数组，直接使用
      let radius = layer.getRadius()
      let latLng = layer.getLatLng()
      //一个自定义的计算长度的函数
      let area = formatCircleArea(radius)
      addMeasureMarker(area, [latLng.lat, latLng.lng], drawGroup)
    }
    // drawGroup,groupLayer,把画图的图层添加到图层组方便管理
    // drawGroup.addLayer(layer);
  })
  // 结束绘制监听
  map.on(L.Draw.Event.DRAWSTOP, function() {
    console.log('结束绘制')
  })
}
const drawMap = (options, map, drawLayerGrounp, _this) => {
  if (options.layerType == 'polygon') {
    let polygon = L.polygon(options.latlng, {
      'stroke': true,
      'color': '#3388ff',
      'weight': 4,
      'opacity': 0.5,
      'fill': true,
      'fillColor': null,
      'fillOpacity': 0.2,
      'clickable': true
    })
    polygon.addTo(drawLayerGrounp)
    map.fitBounds(polygon.getBounds())
  } else if (options.layerType == 'rectangle') {
    let rectangle = L.rectangle(options.latlng, {
      'stroke': true,
      'color': '#3388ff',
      'weight': 4,
      'opacity': 0.5,
      'fill': true,
      'fillColor': null,
      'fillOpacity': 0.2,
      'clickable': true
    }).addTo(map)
    rectangle.addTo(drawLayerGrounp)
    map.fitBounds(options.latlng)
  } else if (options.layerType == 'circle') {
    let circle = L.circle(options.latlng, { radius: options.radius }).addTo(map)
    circle.addTo(drawLayerGrounp)
    map.flyTo(options.latlng)
  } else if (options.layerType == 'marker') {
    const DefaultIcon = L.icon({
      iconUrl: icon,
      iconAnchor: [10, 41]
    })
    L.Marker.prototype.options.icon = DefaultIcon
    L.Marker.prototype.options.title = options.title
    let marker = L.marker([options.latLng.lat, options.latLng.lng], { icon: DefaultIcon }).addTo(map)
    marker.addTo(drawLayerGrounp)
    marker.on('click', (e) => {
      console.log(options, '标注点击事件')
      if (options.type == 'current')
      {
        _this.$router.push({
          path: "/fwkgl/fwkck",
          query: {
            ldid: options.ldid,
            ldids: JSON.stringify(options.ldids)
          }
        })
      }
      else if (options.type == 'all')
      {
        _this.changeType(options.xmid, options.ldid)
      }
    })
  }
}
const addMeasureMarker = (res, latLng, map) => {
  var myIcon = L.divIcon({
    html: res,
    className: 'my-div-icon',
    iconSize: 50
  })
  L.marker(latLng, { icon: myIcon }).addTo(map)
}

const formatArea = (polygon) => {
  //L.GeometryUtil.geodesicArea(),返回number类型的数据，单位是平方米，这里做了一下转化
  var seeArea = L.GeometryUtil.geodesicArea(polygon)
  let area = (seeArea / 10e5).toFixed(2) + 'k㎡'
  return area
}
const formatCircleArea = (radius) => {
  //L.GeometryUtil.geodesicArea(),返回number类型的数据，单位是平方米，这里做了一下转化
  var seeArea = radius * radius * Math.PI
  let area = (seeArea / 10e5).toFixed(2) + 'k㎡'
  return area
}
const formatLength = (line) => {
  let dis = 0
  for (let i = 0; i < line.length - 1; i++) {
    let start = line[i]
    let end = line[i + 1]
    dis += L.latLng([start.lat, start.lng]).distanceTo([end.lat, end.lng])//计算两个点之间的距离，并累加
  }
  //结果得到的也是number类型，单位是 米
  return (dis / 10e2).toFixed(2) + 'km'
}
export default {
  createMap,
  createTileLayer,
  createTDTWMTSLayer,
  createDrawControl,
  createFeatureGroup,
  createMapArea,
  formatArea,
  addMeasureMarker,
  formatCircleArea,
  formatLength,
  drawMap
}
